package com.lingkang.flychat.interceptor;

import com.alibaba.fastjson.JSON;
import com.lingkang.flychat.dto.ResponseResult;
import com.lingkang.flychat.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author linke
 * @date 2020/3/29 14:26
 * @description
 */

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    //在请求处理之前进行调用（Controller方法调用之前)
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            if (redisService.get(String.format("token:%s", token)) != null) {
                return true;
            }
        }
        token = request.getParameter("token");
        if (!StringUtils.isEmpty(token)) {
            if (redisService.get(String.format("token:%s", token)) != null) {
                return true;
            }
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        if (StringUtils.isEmpty(token)) {
            ResponseResult result = new ResponseResult();
            result.setCode(2);
            result.setMessage("token无效");
            response.getWriter().write(JSON.toJSONString(result));
        }
        return false;
    }

    //请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//
//    }

    //在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//
//    }
}
